package com.sample.base.app;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks2;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.loyal.helper.DialogHelper;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;

public class AppLifecycleManager {
    private static final String TAG = AppLifecycleManager.class.getName();

    public void register(Application application) {
        application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                add(activity);
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {
            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {
                Log.e(TAG, "onActivityPaused: " + activity);
            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {
                Log.e(TAG, "onActivityStopped: " + activity);
            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                Log.e(TAG, "onActivityDestroyed: " + activity);
                finish(activity);
            }
        });
        application.registerComponentCallbacks(new ComponentCallbacks2() {

            @Override
            public void onConfigurationChanged(@NonNull Configuration newConfig) {

            }

            @Override
            public void onLowMemory() {

            }

            /*TrimMemoryLevel               level对应的字符串常量	level对应的数字
            TRIM_MEMORY_COMPLETE	        COMPLETE            80
            TRIM_MEMORY_MODERATE	        MODERATE            60
            TRIM_MEMORY_BACKGROUND	        BACKGROUND         	40
            TRIM_MEMORY_UI_HIDDEN	        HIDDEN              20
            TRIM_MEMORY_RUNNING_CRITICAL	RUNNING_CRITICAL    15
            TRIM_MEMORY_RUNNING_LOW     	RUNNING_LOW	        10
            TRIM_MEMORY_RUNNING_MODERATE	RUNNING_MODERATE	5
*/
            @Override
            public void onTrimMemory(int level) {

            }
        });
    }

    private static AppLifecycleManager mInstance;
    /**
     * task map，用于记录activity栈，方便退出程序（这里为了不影响系统回收activity，所以用软引用）
     */
    private final Stack<Activity> activityStack = new Stack<>();

    private AppLifecycleManager() {
    }

    public static AppLifecycleManager getInstance() {
        if (mInstance == null) {
            synchronized (AppLifecycleManager.class) {
                if (null == mInstance)
                    mInstance = new AppLifecycleManager();
            }
        }
        return mInstance;
    }

    /**
     * * 往应用task map加入activity
     */
    public final void add(Activity atv) {
        activityStack.add(atv);
    }

    /**
     * 第一个
     */
    public @Nullable
    Activity first() {
        //if (0==size()) return null;
        try {
            return activityStack.firstElement();
        } catch (NoSuchElementException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 最后一个
     */
    public @Nullable
    Activity last() {
        //if (0==size()) return null;
        try {
            return activityStack.lastElement();
        } catch (NoSuchElementException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishLast() {
        Activity activity = activityStack.lastElement();
        finish(activity);
    }

    /**
     * 结束指定类名的Activity
     */
    public void finish(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finish(activity);
            }
        }
    }

    /**
     * 结束指定的Activity
     */
    public void finish(Activity activity) {
        if (null == activity)
            return;
        Log.e(TAG, "finishActivity: " + activity);
        String key = activity.getClass().getName();
        DialogHelper.remove(key);
        if (!activity.isFinishing() && !activity.isDestroyed())
            activity.finish();
        activityStack.remove(activity);
        activity = null;
    }

    public final int size() {
        return activityStack.size();
    }

    /**
     * * 清除应用的task栈，如果程序正常运行这会导致应用退回到桌面
     */
    public final void clearAll() {
        Iterator<Activity> it = activityStack.iterator();
        while (it.hasNext()) {
            Activity activity = it.next();
            String key = null == activity ? null : activity.getClass().getName();
            DialogHelper.remove(key);
            if (null != activity && !activity.isFinishing()) {
                activity.finish();
            }
            it.remove();
        }
        activityStack.clear();
    }
}
